package com.kupdater.transform;

/**
 * Created by IntelliJ IDEA.
 * User: Jan Ove
 * Date: 29.jan.2009
 * Time: 20:18:42
 * To change this template use File | Settings | File Templates.
 */
import com.kupdater.util.*;
import com.kupdater.Constants;
import com.sun.org.apache.bcel.internal.generic.ClassGen;
import com.sun.org.apache.bcel.internal.generic.Type;
import com.sun.org.apache.bcel.internal.classfile.Method;
import com.sun.org.apache.bcel.internal.classfile.Field;

import java.util.List;

public class RSStringTransformer extends Transformer {
	@Override
	public Class<?>[] getDependencies() {
		return Constants.NO_DEPENDENCIES;
	}

	@Override
	public boolean isApplicable(ClassGen cG) {
        int foundEquals = 0;
        int foundToString = 0;
        for(Method method: cG.getMethods()){
            if(method.getName().equals("equals"))
                foundEquals++;
            if(method.getName().equals("toString"))
                foundToString++;
        }
        return (foundEquals == 1 && foundToString == 1);
	}

	@Override
	public boolean transform(ClassGen cG) {
        TransformUtils.classesShouldDefine++;
        String idName = this.getClass().getSimpleName().replaceAll("Transformer", "");
		String hookName = Constants.PACKAGE_HOOK + "." + idName;
		classMap.put(idName, cG);
		TransformUtils.addInterface(this, cG, hookName);

        for(Field field: cG.getFields()){
            if(field.getType() == Type.INT && field.getAccessFlags() == 0){
                TransformUtils.injectGetMethod(this, cG, field, "getLength");
            }
            else if(field.getType() == Type.BOOLEAN && field.isPrivate()){
                TransformUtils.injectGetMethod(this, cG, field, "isEditable");
            }
            else if(field.getType().getSignature().equals("[B") && field.getAccessFlags() == 0){
                TransformUtils.injectGetMethod(this, cG, field, "getBytes");
            }
        }
        TransformUtils.fieldsShouldHook += 3;
		return true;
	}
}

